<?php
/**
 * Created by PhpStorm.
 * User: zhaoyi
 * Date: 2022/1/26
 * Time: 11:46.
 */

declare(strict_types=1);

namespace App\Application\Api\Controller;

use App\Annotation\Api;
use App\Application\Admin\Model\Store;
use App\Application\Admin\Service\AdminSettingService;
use Hyperf\Codec\Xml;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;

#[Controller("/api/Wecat/")]
class WecatController extends AbstractController
{
    #[Inject]
    protected AdminSettingService $setting;

    #[Api]
    #[PostMapping("index")]
    function index()
    {
        $order_on = $this->request->input('order_on', '');
        $type = $this->request->input('type', '');
        //type 1:会员充值 2:xxxx ,3:包厢预订，

        switch ($type) {
            case '1':
                $order = Db::table('vip_order')->where('order_on', $order_on)->first() ?: [];
                $body = '会员充值';
                break;
            case '2':
                $order = Db::table('product_order')->where('order_on', $order_on)->first() ?: [];
                $body = '会员充值';
                break;
            case '3':
                $order = Db::table('order')->where('order_on', $order_on)->first() ?: [];
                $body = '包厢预订';
                break;
            default:
                $body = '';
                return $this->returnErrorJson('订单不存在');

        }
        //订单 状态 订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款
        if ($order->pay_status==0) {
            $this->returnErrorJson('该订单已付款');
        }
        if ($order->pay_status==4) {
            $this->returnErrorJson('该订单付款超时');
        }
        $store = Db::table('store')->where('store_id', $order->store_id)->first() ?: [];
        $user = $this->checkToken();
        if (empty($user)) {
            return $this->returnErrorJson('请先登录');
        }
        $appId = $this->setting->getSiteSetting('app_id');;
        $mch_id = $this->setting->getSiteSetting('sub_mch_id');
        $api_key = $this->setting->getSiteSetting('apikey');
        $parameters = array(
            'appid' => $appId, //小程序ID
            'mch_id' => $mch_id, //商户号
            'sub_appid' => $appId, //小程序ID
            'sub_mch_id' => $store->sub_mch_id, //子商户商户号
            'nonce_str' => $this->createNoncestr(), //随机字符串
            'body' => $body,
            'notify_url' => $this->setting->getSiteSetting('url') . '/api/Wecat/callback', //通知地址 确保外网能正常访问
            'out_trade_no' => $order_on,
            'total_fee' => (int)(($order->price) * 100),
            'spbill_create_ip' => $this->getClientIp() ?? '47.120.23.131', //终端IP
            'profit_sharing' => 'Y',
            'openid' => $user->openid, //用户id
            'trade_type' => 'JSAPI'//交易类型

        );
        //统一下单签名

        $parameters['sign'] = $this->getSignwx($parameters, 'MD5', $api_key);
        $xmlData = $this->arrayToXml($parameters);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $payinfo = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));

        if ($payinfo['return_code'] == 'SUCCESS') {
            $time = time();
            $parameter = array(
                'appId' => $appId, //小程序ID
                'timeStamp' => (string)$time, //时间戳
                'nonceStr' => $this->createNoncestr(), //随机串
                'package' => 'prepay_id=' . $payinfo['prepay_id'], //数据包
                'signType' => 'MD5'//签名方式
            );
            //签名
            $parameter['paySign'] = $this->getSignwx($parameter, 'MD5', $api_key);
            $msg = $payinfo['err_code_des'];
            if ($msg) {
                return $this->returnErrorJson($msg);
            } else {
                return $this->returnSuccessJson(compact('parameter', 'payinfo', 'parameters'));

            }
        } else {
            $msg = $payinfo['return_msg'];
            return $this->returnErrorJson($msg);
        }


    }

    // 微信支付回调

    /**
     * 微信支付回调
     *
     */
    #[Api]
    #[PutMapping("callback")]
    public function callback()
    {
        // 记录日志

        $notifiedData = file_get_contents('php://input');


//        $params = '<xml><appid><![CDATA[wx2acb0b4eeae1e47c]]></appid>
//<bank_type><![CDATA[OTHERS]]></bank_type>
//<cash_fee><![CDATA[1]]></cash_fee>
//<fee_type><![CDATA[CNY]]></fee_type>
//<is_subscribe><![CDATA[N]]></is_subscribe>
//<mch_id><![CDATA[1649997900]]></mch_id>
//<nonce_str><![CDATA[a9cpjorw9hg7gc3211loieqmfunmdyha]]></nonce_str>
//<openid><![CDATA[odlXJ6-qRdalpO-8jUOqaY0FJva8]]></openid>
//<out_trade_no><![CDATA[202404161436564035]]></out_trade_no>
//<result_code><![CDATA[SUCCESS]]></result_code>
//<return_code><![CDATA[SUCCESS]]></return_code>
//<sign><![CDATA[26E413674348CFD5F843042624109993]]></sign>
//<time_end><![CDATA[20240416143711]]></time_end>
//<total_fee>1</total_fee>
//<trade_type><![CDATA[JSAPI]]></trade_type>
//<transaction_id><![CDATA[4200002165202404161442622427]]></transaction_id>
//</xml>';

        file_put_contents('./runtime/logs/wxpay.txt', date('Y-m-d H:i:s') . ($notifiedData) . PHP_EOL, FILE_APPEND);
        return $notifiedData;
        //XML格式转换
        $xmlObj = simplexml_load_string($notifiedData, 'SimpleXMLElement', LIBXML_NOCDATA);
        $data = json_decode(json_encode($xmlObj), true);
        file_put_contents('./runtime/logs/wxpay.txt', date('Y-m-d H:i:s') . json_encode($data) . PHP_EOL, FILE_APPEND);

        $sign_return = $data['sign'];
        //支付成功
        unset($data['sign']);
        $api_key = $this->setting->getSiteSetting('apikey');
        $sign = $this->getSignwx($data, 'MD5', $api_key);

        if ($data['return_code'] == "SUCCESS" && $data['result_code'] == "SUCCESS" && $sign === $sign_return) {
            $orderNo = $data['out_trade_no'];
            Db::startTrans();


            Db::commit();


            $this->returnCode(true, 'OK');
        }
    }


}